<?php

namespace app\core\forms\user;

use app\core\entities\User;
use yii\base\Model;
use yii\helpers\ArrayHelper;
use Yii;

class UserForm extends Model
{
    public ?string $username = '';
    public ?string $email = '';
    public ?string $password = '';
    public ?string $role = '';

    public User $_user;

	public function __construct(User $user = null, $config = [])
	{
		if ($user) {
			$this->username = $user->username;
			$this->email    = $user->email;
			$roles          = Yii::$app->authManager->getRolesByUser( $user->id );
			$this->role     = $roles ? reset( $roles )->name : null;
			$this->_user    = $user;
		}
		parent::__construct($config);
	}

	public function rules(): array
	{
		return [
			[['username', 'email', 'role'], 'required'],
            ['email', 'trim'],
			['email', 'email'],
			['email', 'string', 'max' => 255],
			[['email'], 'unique', 'targetClass' => User::class, 'filter' => isset($this->_user->id) ? ['<>', 'id', $this->_user->id] : null ],
			['password', 'string', 'min' => 8],
		];
	}

    public function rolesList(): array
    {
        return ArrayHelper::map(Yii::$app->authManager->getRoles(), 'name', 'description');
    }
}
